const HtmlWebpackPlugin = require('safe-require')('html-webpack-plugin')

import { Hooks } from 'html-webpack-plugin'
import { Compilation } from 'webpack'
import generateResourceMonitor from './resourceMonitor'
import { validateResource } from './utils'

export function supportHtmlWebpackPlugin() {
  return !!HtmlWebpackPlugin?.getHooks
}

export function pluginHandle(pluginName: string, compilation: Compilation) {
  const hooks: Hooks = HtmlWebpackPlugin.getHooks(compilation)

  hooks.alterAssetTags.tapPromise(pluginName, data => {
    return new Promise((resolve, reject) => {
      const scriptResourceSetUrlSegment: Array<string> = []
      const linkResourceUrlSegment: Array<string> = []

      data.assetTags.scripts.forEach((script) => {
        if (script.attributes.src && validateResource(String(script.attributes.src))) {
          scriptResourceSetUrlSegment.push(`['${script.attributes.src}', false]`)
        }
        script.attributes.onerror = '__onResourceLoadError__(this, { delay: 1000 })'
        script.attributes.onload = '__onResourceLoad__(this)'
      })

      data.assetTags.styles.forEach((style) => {
        if (style.attributes.href && validateResource(String(style.attributes.href))) {
          linkResourceUrlSegment.push(`['${style.attributes.href}', false]`)
        }
        style.attributes.onerror = '__onResourceLoadError__(this, { delay: 1000 })'
        style.attributes.onload = '__onResourceLoad__(this)'
      })

      const resourceMonitor = generateResourceMonitor({
        links: linkResourceUrlSegment.join(', '),
        scripts: scriptResourceSetUrlSegment.join(', ')
      })

      data.assetTags.scripts.unshift({
        tagName: 'script',
        voidTag: false,
        attributes: {},
        meta: {},
        innerHTML: resourceMonitor
      })
      
      resolve(data)
    })
  })
}